package com.avic.rong;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.v7.app.ActionBar;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.product.OnlineCServiceActivity;
import com.avic.rong.bean.CartListReloadEvent;
import com.avic.rong.bean.GoCartListEvent;
import com.avic.rong.bean.HomePageEvent;
import com.avic.rong.bean.MinePageEvent;
import com.avic.rong.goodsSort.CarView;
import com.avic.rong.network.Constant;
import com.avic.rong.publishVideo.MyProgressDialog;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.utils.OnClickLimitListener;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.wedgit.NXHooldeView;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;
import com.umeng.message.PushAgent;


import org.greenrobot.eventbus.EventBus;

import butterknife.ButterKnife;
import cn.bingoogolapple.swipebacklayout.BGASwipeBackHelper;


public abstract class BaseActivity extends RxAppCompatActivity implements BGASwipeBackHelper.Delegate {
    public static final String TAG = BaseActivity.class.getSimpleName();

    private View statusBarView;
    protected Context context;
    protected Bundle bundle;
    protected TextView tvTitle;
    protected ImageView ivBack;
    protected ImageView ivRight;
    protected TextView tvRight;
    //是否需要导航栏  默认需要
    protected boolean isNeedTitle = true;
    private SharedPreferencesUtil sharedPreferencesUtil;

    private MyApplication application;
    private BaseActivity oContext;
    private View popView;
    private PopupWindow popupWindow;
    protected BGASwipeBackHelper mSwipeBackHelper;

    public Integer pageSize = 20;
    public Integer currentPageNumber = 1;
    public boolean isRefresh = false;
    private LinearLayout llRoot;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        if (getContentViewId() != 0) {
            setContentView(getContentViewId());
            //必须在setContentView之后
            ButterKnife.bind(this);
        }

        context = this;
        PushAgent.getInstance(context).onAppStart();
        if (getIntent().getBundleExtra(Constant.START_ACTIVITY_PUTEXTRA) != null) {
            bundle = getIntent().getBundleExtra(Constant.START_ACTIVITY_PUTEXTRA);
        }
        if (isNeedTitle) {
            initTitleView();
        }
        initView();
        addListener();
        //退出应用（为了防止栈顶模式）
        exitUse();

        //延时加载数据.
        Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                if (isStatusBar()) {
                    initStatusBar();
                    getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
                        @Override
                        public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                            initStatusBar();
                        }
                    });
                }
                //只走一次
                return false;
            }
        });


        initSwipeBackFinish();
        overridePendingTransition(R.anim.slide_in_right, R.anim.keep);


    }


    private void initStatusBar() {
        if (statusBarView == null) {
            int identifier = getResources().getIdentifier("statusBarBackground", "id", "android");
            statusBarView = getWindow().findViewById(identifier);
        }
        if (statusBarView != null) {
            statusBarView.setBackgroundResource(R.drawable.status_bar_title);
        }
    }

    protected boolean isStatusBar() {
        return true;
    }

    private void exitUse() {
        if (application == null) {
            // 得到Application对象
            application = (MyApplication) getApplication();
        }
        oContext = this;// 把当前的上下文对象赋值给BaseActivity
        addActivity();// 调用添加方法
    }


    // 添加Activity方法
    public void addActivity() {
        application.addActivity_(oContext);// 调用myApplication的添加Activity方法
    }

    //销毁当个Activity方法
    public void removeActivity() {
        application.removeActivity_(oContext);// 调用myApplication的销毁单个Activity方法
    }

    //销毁所有Activity方法
    public void removeALLActivity() {
        application.removeALLActivity_();// 调用myApplication的销毁所有Activity方法
    }

    /***
     * 进入页面
     *
     * @param cla
     * @param bundle
     */
    public void enterPage(Class<?> cla, Bundle bundle) {
        if (cla == null) {
            return;
        }
        enterPageForResult(cla, bundle, 0);
    }

    /***
     * 进入页面
     *
     * @param cla
     * @param requestCode
     */
    public void enterPageForResult(Class<?> cla, int requestCode) {
        if (cla == null) {
            return;
        }
        enterPageForResult(cla, null, requestCode);
    }

    /***
     * 进入页面
     *
     * @param cla
     * @param bundle
     * @param requestCode 请求码
     */
    public void enterPageForResult(Class<?> cla, Bundle bundle, int requestCode) {
        if (cla == null) {
            return;
        }
        Intent intent = new Intent(context, cla);
        if (bundle != null) {
            intent.putExtra(Constant.START_ACTIVITY_PUTEXTRA, bundle);
        }
        if (requestCode > 0) {
            startActivityForResult(intent, requestCode);
        } else {
            startActivity(intent);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public SharedPreferencesUtil getSharedPreferencesUtil() {
        if (sharedPreferencesUtil == null) {
            sharedPreferencesUtil = SharedPreferencesUtil.getInstance(context);
        }
        return sharedPreferencesUtil;
    }

    private void initTitleView() {
        tvTitle = findViewById(R.id.tv_title);
        tvRight = findViewById(R.id.tv_right);
        ivBack = findViewById(R.id.iv_back);
        ivRight = findViewById(R.id.iv_right);
        llRoot = findViewById(R.id.ll_root);
        if (ivBack != null) {
            ivBack.setOnClickListener(new OnClickLimitListener() {
                @Override
                public void onClickLimit(View v) {
                    finish();
                }
            });
        }
        if (tvTitle != null) {
            tvTitle.setText(getViewTitle());
        }

        if (ivRight != null) {
            ivRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPopup(BaseActivity.this, llRoot);
                }
            });
        }
    }

    protected void showPopup(BaseActivity baseActivity, View view) {
        commonPop(view);
        initListener(baseActivity);
    }

    ;

    /*
     * 功能直达蒙层
     * */
    private void commonPop(View view) {
        popView = LayoutInflater.from(this).inflate(R.layout.function_of_direct, null, false);
        popupWindow = new PopupWindow(popView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
       /* // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);*/
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setClippingEnabled(false);
        //从上往下弹出动画效果
        popupWindow.setAnimationStyle(R.style.topPopupAnimation);
        popupWindow.showAtLocation(view, Gravity.TOP, 0, 0);
    }

    private void initListener(Context context) {
        ImageView img_close_pop = popView.findViewById(R.id.img_close_pop);
        Button bt_home = popView.findViewById(R.id.bt_home);
        Button bt_mall = popView.findViewById(R.id.bt_mall);
        Button bt_news = popView.findViewById(R.id.bt_news);
        Button bt_own = popView.findViewById(R.id.bt_own);
        Button bt_goods_car = popView.findViewById(R.id.bt_goods_car);
        Button bt_kefu = popView.findViewById(R.id.bt_kefu);

        img_close_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        bt_home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new HomePageEvent());
                Intent intent = MainActivity.queryIntent(context);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
        bt_mall.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                EventBus.getDefault().postSticky(new GoCartListEvent());
                Intent intent = MainActivity.queryIntent(context);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
            }
        });
        bt_news.setOnClickListener(new View.OnClickListener() {//消息
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new CartListReloadEvent());
                    Intent intent = MainActivity.queryIntent(context);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }else {
                    startActivity(LoginPhoneActivity.getIntent(context,"CartListReloadEvent---"));
                }
            }
        });
        bt_own.setOnClickListener(new View.OnClickListener() {//我的
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    EventBus.getDefault().postSticky(new MinePageEvent());
                    Intent intent = MainActivity.queryIntent(context);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(intent);
                }else {
                    startActivity(LoginPhoneActivity.getIntent(context,"MinePageEvent---"));
                }
            }
        });
        bt_goods_car.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                startActivity(ShoppingCarActivity.queryIntent(context));
            }
        });
        bt_kefu.setOnClickListener(new View.OnClickListener() {//客服
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
                if (SharedPreferencesUtil.isLogin()) {
                    startActivity(OnlineCServiceActivity.getIntent(context, "123456"));
                }else {
                    startActivity(LoginPhoneActivity.getIntent(context,"OnlineCServiceActivity----"));
                }
            }
        });


    }


    /***
     * 获取布局
     *
     * @return
     */
    protected abstract int getContentViewId();

    /***
     * 初始化view
     */

    protected abstract void initView();

    /***
     * 注册监听器
     */
    protected abstract void addListener();

    /***
     * 获取标题
     * @return
     */
    protected String getViewTitle() {
        return context.getResources().getString(R.string.app_name);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

    }


    protected <T extends View> T $(int id) {
        return (T) super.findViewById(id);
    }


    /**
     * 初始化滑动返回。在 super.onCreate(savedInstanceState) 之前调用该方法
     */
    private void initSwipeBackFinish() {
        mSwipeBackHelper = new BGASwipeBackHelper(this, this);

        // 「必须在 Application 的 onCreate 方法中执行 BGASwipeBackHelper.init 来初始化滑动返回」
        // 下面几项可以不配置，这里只是为了讲述接口用法。

        // 设置滑动返回是否可用。默认值为 true
        mSwipeBackHelper.setSwipeBackEnable(true);
        // 设置是否仅仅跟踪左侧边缘的滑动返回。默认值为 true
        mSwipeBackHelper.setIsOnlyTrackingLeftEdge(true);
        // 设置是否是微信滑动返回样式。默认值为 true
        mSwipeBackHelper.setIsWeChatStyle(true);
        // 设置阴影资源 id。默认值为 R.drawable.bga_sbl_shadow
        mSwipeBackHelper.setShadowResId(R.drawable.bga_sbl_shadow);
        // 设置是否显示滑动返回的阴影效果。默认值为 true
        mSwipeBackHelper.setIsNeedShowShadow(true);
        // 设置阴影区域的透明度是否根据滑动的距离渐变。默认值为 true
        mSwipeBackHelper.setIsShadowAlphaGradient(true);
        // 设置触发释放后自动滑动返回的阈值，默认值为 0.3f
        mSwipeBackHelper.setSwipeBackThreshold(0.3f);
        // 设置底部导航条是否悬浮在内容上，默认值为 false
        mSwipeBackHelper.setIsNavigationBarOverlap(false);
    }

    /**
     * 是否支持滑动返回。这里在父类中默认返回 true 来支持滑动返回，如果某个界面不想支持滑动返回则重写该方法返回 false 即可
     *
     * @return
     */
    @Override
    public boolean isSupportSwipeBack() {
        return true;
    }

    /**
     * 正在滑动返回
     *
     * @param slideOffset 从 0 到 1
     */
    @Override
    public void onSwipeBackLayoutSlide(float slideOffset) {
    }

    /**
     * 没达到滑动返回的阈值，取消滑动返回动作，回到默认状态
     */
    @Override
    public void onSwipeBackLayoutCancel() {
    }

    /**
     * 滑动返回执行完毕，销毁当前 Activity
     */
    @Override
    public void onSwipeBackLayoutExecuted() {
        mSwipeBackHelper.swipeBackward();
    }

    @Override
    public void onBackPressed() {
        // 正在滑动返回的时候取消返回按钮事件

        if (mSwipeBackHelper.isSliding()) {
            return;
        }
        mSwipeBackHelper.backward();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.keep, R.anim.out_from_right);
    }

    public static Intent getIntent(Context context, Class className) {
        Intent intent = new Intent(context, className);
        return intent;
    }


    /**
     * 加入购物车动画
     *
     * @param addView
     * @param numberView
     */
    public void addProductionAnimation(View addView, CarView numberView) {
        NXHooldeView nxHooldeView = new NXHooldeView(this);
        nxHooldeView.setControlPointPositionUp(false);
        int position[] = new int[2];
        addView.getLocationInWindow(position);
        nxHooldeView.setStartPosition(new Point(position[0] + addView.getWidth() / 2, position[1]));
        ViewGroup rootView = (ViewGroup) this.getWindow().getDecorView();
        rootView.addView(nxHooldeView);
        int endPosition[] = numberView.getLocation();
//        numberView.getLocationInWindow(endPosition);
        nxHooldeView.setEndPosition(new Point(endPosition[0] + numberView.getWidth() / 2 - NXHooldeView.VIEW_SIZE / 2, endPosition[1]));
        nxHooldeView.startBeizerAnimation();
    }

    private MyProgressDialog dialog;

    protected void showDialog(String message) {
        this.showDialog("", message);
    }

    protected void showDialog(String title, String message) {
//        if (dialog2 == null || !dialog2.isShowing()) {// 如果不存在，或者没有正在显示，则创建新的dialog并显示
//            dialog2 = ProgressDialog.show(this, title, message);
//        } else {// 否者直接修改现有dialog的title与message
//            dialog2.setTitle(title);
//            dialog2.setMessage(message);
//        }


        if (dialog == null || !dialog.isShowing()) {
            dialog = MyProgressDialog.createDialog(this);
            dialog.setMessage(message);
        }

        dialog.show();
    }


    protected void dismissDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (dialogTitle != null && dialogTitle.isShowing()) {
            dialogTitle.dismiss();
        }
    }

    public void showProgressDialog(String message) {
        this.showDialog("", message);
    }

    public void dismissProgressDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (dialogTitle != null && dialogTitle.isShowing()) {
            dialogTitle.dismiss();
        }
    }


    /**
     * 最新的loading  后续的慢慢替换
     *
     * @param message
     */
    protected void startLoading(String message) {
        if (dialog == null || !dialog.isShowing()) {
            dialog = MyProgressDialog.createDialog(this);
            dialog.setMessage(message);
        }
        dialog.show();
    }

    protected void stopLoading() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }


    private ProgressDialog dialogTitle;

    protected void showDialogTitle(String message) {
        this.showDialogTitle("", message);
    }

    protected void showDialogTitle(String title, String message) {
        if (dialogTitle == null || !dialogTitle.isShowing()) {// 如果不存在，或者没有正在显示，则创建新的dialog并显示
            dialogTitle = ProgressDialog.show(this, title, message);
        } else {// 否者直接修改现有dialog的title与message
            dialogTitle.setTitle(title);
            dialogTitle.setMessage(message);
        }


        dialogTitle.show();
    }


    protected void dismissDialogTitle() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        if (dialogTitle != null && dialogTitle.isShowing()) {
            dialogTitle.dismiss();
        }

    }


}
